<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 笔记：28.1-1.3-2.ajax封装 -->
    <script>
      // c3 c6
      function ajax(options) {
        let xhr = new XMLHttpRequest()
        // c14
        let params = ''
        // c15
        for (let pName in options.data) {
          params += `${pName}=${options.data[pName]}&`
        }
        // c16
        // params = params.substr(0, params.length - 1)
        params = params.slice(0, -1)
        // console.log('params',params)

        // c17
        if (options.type == 'get') {
          options.url = options.url + '?' + params
        }

        // c4 c7
        xhr.open(options.type, options.url)

        // c18
        if (options.type == 'post') {
          let contentType = options.header['Content-Type']
          //c18.1 还要改变请求报文，post请求，必须在请求报文中明确请求参数的类型
          // c20
          xhr.setRequestHeader('Content-Type', contentType)
          // c22
          if (contentType == 'application/json') {
            xhr.send(JSON.stringify(options.data))
          } else {
            xhr.send(params)
          }
        } else {
          xhr.send()
        }

        // c8
        // xhr.send()
        // c9
        xhr.onload = function () {
          // console.log(xhr.responseText)
          // c11
          // options.then(xhr.responseText)

          // c23
          if (xhr.status == 200) {
            options.then(xhr.responseText)
          } else {
            options.catch(xhr.responseText, xhr)
          }
        }
      }
      // c5
      ajax({
        type: 'get',
        url: 'http://localhost:3000/first',
        // c13
        data: {
          name: 'zhangs',
          age: 20
        },
        // c19 c21
        header: {
          'Content-Type': 'application/json'
        },
        // c10 c12
        then(data) {
          console.log('这里是then' + data)
        },
        // c24
        catch(res, xhr) {
          console.log('错误：' + res)
          console.log(xhr)
        }
      })
    </script>
  </body>
</html>
